package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.sso.enums.SexEnum;
import com.tanhua.sso.mapper.UserInfoMapper;
import com.tanhua.sso.pojo.User;
import com.tanhua.sso.pojo.UserInfo;
import com.tanhua.sso.vo.PicUploadResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Service
public class UserInfoService {
    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private FaceEngineService faceEngineService;

    @Autowired
    private PicUploadService picUploadService;

    //基本信息
    public boolean saveUserInfo(Map<String, String> params, String token) {
        //校验token
        User user=this.userService.queryUserByToken(token);
        if (user==null){
            return false;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setSex(StringUtils.equals(params.get("gender"),"man")? SexEnum.MAN:SexEnum.WOMAN);
        userInfo.setNickName(params.get("nickname"));
        userInfo.setBirthday(params.get("birthday"));
        userInfo.setCity(params.get("city"));



        return userInfoMapper.insert(userInfo)==1;
    }

    //保存头像
    public boolean  saveUserLogo(MultipartFile file, String token) {

        //校验token
        User user=this.userService.queryUserByToken(token);
        if (user==null){
            return false;
        }

        //校验logo是否为人像
        try {
            boolean isPortrait = faceEngineService.checkIsPortrait(file.getBytes());
            if (!isPortrait){
                //非人像，返回false
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

            //是人像， 上传到阿里云
        PicUploadResult result = picUploadService.upload(file);
        if(StringUtils.isEmpty(result.getName())){
            //上传失败
            return false;
        }
        //上传成功，保存到用户信息当中
        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(result.getName());

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId());

        boolean b = this.userInfoMapper.update(userInfo, queryWrapper) == 1;
        return b;
    }
}
